import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';

import { CategoryName } from '../../pipes/categoryNamePipe';
import { Util } from '../../utils/util';
import { TreeService } from './tree.service';
import { Subscription } from 'rxjs/Subscription';
declare var $: any;
@Component({
  selector: 'ng-tree',
  templateUrl: './tree.html',
  styleUrls: ['./tree.css'],
  providers: [TreeService]
})

export class NgTree {

  @Input('option') option: any;

  /*Option

  cat:any = {}

  defaultText:boolean

  noLeaf:boolean

  onlyLeaf:boolean

  placeholder:string

  all:boolean

  */

  // @Input('data') data:any;
  tree: any = [];

  @Output('onChangeCat') onChangeCat: EventEmitter<any> = new EventEmitter<any>();

  constructor(private service: TreeService, private util: Util, private CategoryName: CategoryName) { }

  // 菜单的展示控制
  menuShowControl: boolean = false;

  viewMadieControl: boolean = false;

  // emitdata
  emitData = {
    wholeName: "",
    categoryId: "",
    catName: ""
  };

  ngOnInit() {
    // 点击取消
    $(document.body).on("click", (e) => {

      // 在界面，里点击·1
      if ($(".itemInnerAll").find($(e.target)).length > 0) {
        return;
      }


      if (this.menuShowControl === true) {

        this.menuShowControl = false;
        e.stopPropagation();
      }

    });


    // 是否是PC，phone
    if ($(document.body).width() < 1024) {

      this.viewMadieControl = true;//Phone

    } else {

      this.viewMadieControl = false;//PC
    }

    this.dataInit();
  }

  // click menu toggel
  toggelElement(e) {

    this.menuShowControl = !this.menuShowControl;

    console.log(this.menuShowControl);

    e.stopPropagation();
  }

  // Output
  emitDataInit(data) {

    this.emitData.catName = data.catName;

    this.emitData.categoryId = data.categoryId;

    this.emitData.wholeName = data.categoryName;

    this.onChangeCat.emit(this.emitData);
  }

  // 打开历史
  historyStoreExpand() {

    // alert(0);



    if (this.option && typeof (this.option.cat) != "undefined") {

      let historyArry = [];


      let catName = this.option.cat.wholeName;

      this.emitDataInit(this.option.cat);

      console.log("hjhhhh");
      console.log(catName);

      // 不存在
      if (!catName) {
        this.emitData.catName = "全类目";
        return;
      }

      if (catName.indexOf('--') != -1) {

        historyArry = catName.split('--');

        this.tree.forEach((item) => {

          // 分支扩展
          if (item.catName == historyArry[1]) {
            this.nodeExpand(item, historyArry);
          }
        });

      } else {

        historyArry.push(catName);
      }

    } else {
      // 默认值

      console.log(this.option);
      // placeholder
      if (this.option && typeof (this.option.placeholder) != "undefined") {


        this.emitData.catName = this.option.placeholder;
        return;
      }

      // alert(1);
      this.tree[0].active = true;

      this.emitDataInit(this.tree[0]);
    }

  }


  firstNodeEvent: Subscription;
  dataInit() {


    var res = {"code":0,"msg":"成功","data":[{"id":964,"type":4,"target":"50019780","userId":5,"value":"数码/手机/家电--平板电脑/MID","createTime":1508895423000}]};

      let _data: any = [];

      // 只有一个类目
      if (res.data.length == 1) {
        this.oneIndustry(res.data[0]);
        return;

      }

      // 多个类目
      for (let i in res.data) {

        let item = res.data[i];

        let _item: any = {};

        // 是否有分支children
        if (Number(item.target) > 0 || (this.option && this.option.noLeaf)) {
          _item = {
            level: 2,
            catName: this.CategoryName.transform(item.value),
            categoryName: item.value,
            categoryId: item.target,
            active: false
          };
        } else {
          _item = {
            level: 2,
            catName: this.CategoryName.transform(item.value),
            categoryName: item.value,
            categoryId: item.target,
            active: false,
            children: []
          };
        }


        _data.push(_item);
      }

      if (this.option && this.option.all) {
        _data.unshift({
          level: 2,
          catName: '全类目',
          categoryName: "",
          categoryId: "-1",
          active: false
        });
      }

      this.tree.length = 0;
      this.tree = _data;

      this.historyStoreExpand();



  }

  oneIndustry(_target) {


    console.log("target");

    console.log(_target);

    let obj = {
      level: 2,
      catName: this.CategoryName.transform(_target.value),
      categoryName: _target.value,
      categoryId: _target.target,
      active: true
    };

    this.emitDataInit(obj);

    let json = {
      catName: obj.categoryName,
      level: obj.level + 1
    };

    // this.nodeExpandEvent = this.service.getExpand(json).subscribe((res: any) => {

    //   let _data = this.treeItemInit(res.data);

    //   _data.unshift(obj);

    //   this.tree.length = 0;
    //   this.tree = _data;

    // });



  }

  // 扩展分支，分支定位
  nodeExpandEvent: Subscription;
  nodeExpand(_item, _history: any = false) {

    _item.active = true;

    // 没有children或者已经有children（已经请求过一次）
    if (typeof (_item.children) === 'undefined' || _item.children.length > 0) {
      return;
    }


    let json = {
      catName: _item.categoryName,
      level: _item.level + 1
    };

    this.nodeExpandEvent = this.service.getExpand(json).subscribe((res: any) => {

      _item.children = this.treeItemInit(res.data);

      // 历史
      if (_history) {

        _item.children.forEach((item) => {

          // 分支扩展
          if (item.catName == _history[_item.level - 1]) {
            this.nodeExpand(item, _history[_item.level - 1]);
          }
        });

      }

    });
  }

  // click
  nodeLick(item, e) {
    e.stopPropagation();
    e.preventDefault();

    // 只能点击叶子类目
    if (this.option && typeof (this.option.onlyLeaf) != "undefined") {

      // 叶子类目categoryId<0
      if (item.categoryId < 0) {
        this.nodeSelected(item, e);
        return;
      }

    }



    // console.log(item);
    this.closeActiveUp(item);
    this.emitDataInit(item);
    this.menuShowControl = false;

  }

  // click,levelIndex
  nodeSelected(item, e) {
    e.stopPropagation();
    e.preventDefault();


    // phone
    if (this.viewMadieControl) {

      // 如果是active状态，去除
      if (item.active) {

        this.close(item);

      } else {
        // console.log(item);
        this.closeActiveUp(item);

        this.nodeExpand(item);

        this.holdFixed(e);
      }


    } else {//PC

      // console.log(item);
      this.closeActiveUp(item);

      this.nodeExpand(item);

      this.holdFixed(e);
    }
  }


  // scroll set top
  holdFixed($event) {

    console.log($event.target);

    let aObj;
    // element
    if ($event.target.nodeName == "I") {
      aObj = $($event.target).parent();
    } else {
      aObj = $($event.target);
    }

    let clickLiObj = aObj.parent().parent();

    let itemInnerBoxObj = clickLiObj.parent().parent();

    console.log(clickLiObj.offset().top);
    console.log(itemInnerBoxObj.offset().top);
    console.log(itemInnerBoxObj.scrollTop());




    let Top = clickLiObj.offset().top - itemInnerBoxObj.offset().top;

    let openLevel = clickLiObj.children('.itemInner');
    console.log(openLevel.css('top'));
    if (itemInnerBoxObj.scrollTop() == 0) {
      console.log('已设置过top值');

      // margin-top: -36px;
      openLevel.css({ "margin-top": "-36px" });
    } else {
      openLevel.css({ "top": Top + "px" });
    }



  }

  // treeInit
  treeItemInit(data) {

    let _data: any = [];

    for (let i in data) {

      let item = data[i];

      let _item: any = {};

      // 没有children
      if (Number(item.id) > 0) {

        _item = {
          level: item.level,
          catName: this.CategoryName.transform(item.wholeName),
          categoryName: item.wholeName,
          categoryId: item.id,
          active: false
        };

      } else {

        _item = {
          level: item.level,
          catName: this.CategoryName.transform(item.wholeName),
          categoryName: item.wholeName,
          categoryId: item.id,
          active: false,
          children: []
        };

      }

      _data.push(_item);
    }

    return _data;
  }

  // 同级及下级都检查是否active
  closeActiveUp(item) {

    let cat = item.categoryName;

    let activeList = cat.split('--');

    // console.log(activeList);

    // 删除第一个根类目
    activeList.shift();



    console.log(activeList);
    // 如果长度大于1的
    if (activeList.length > 1) {

      activeList.pop();

      let _tree = this.tree;
      // 查找该item'同级及下级都检查是否active
      for (let i = 0; i < activeList.length; i++) {

        for (let item of _tree) {
          if (item.catName == activeList[i]) {
            _tree = item.children;
          }
        }
      }
      console.log("当前item的的父");
      console.log(_tree);

      this.allHide(_tree);


    } else {//第1级类目
      this.allHide();

    }

    item.active = true;

    console.log(item);

  }



  // 全部去除active
  allHide(tree = this.tree) {

    tree.forEach(item => {
      this.close(item);
    });
  }

  // 关闭
  close(item) {
    item.active = false;
    if (typeof (item.children) !== "undefined") {
      for (let i of item.children) {
        if (i.active === true) {
          this.close(i);
        }
      }
    }
  }

  open(item) {
    item.active = true;

    if (item.children) {
      for (let i of item.children) {
        this.open(i);
      }
    }
  }



  ngOnDestroy() {
    if (this.firstNodeEvent) {
      this.firstNodeEvent.unsubscribe();
    }

    if (this.nodeExpandEvent) {
      this.nodeExpandEvent.unsubscribe();
    }

    // 点击取消
    $(document.body).off("click");
  }
}
